package org.molamil.acto.utils {
	import flash.display.Stage;		import flash.display.DisplayObjectContainer;		import flash.display.DisplayObject;	
	
	/**
	 * XXX: Document.
	 * 
	 * @author Jorge Hernandez
	 */
	public class DisplayUtils {

		
		// PUBLIC METHODS
		
		public static function findChild(root:DisplayObjectContainer, path:String):DisplayObject {
			
			if (root == null)
				return null;
				
			var displayObject:DisplayObject = root;
			
			var a:Array = path.split(".");
			for (var i:uint = 0; i < a.length; i++) {
				if (displayObject is DisplayObjectContainer) {
					var s:String = a[i];
					var sIndexOf:int = s.indexOf("[");
					var name:String=sIndexOf==-1?s.substring(0):s.substring(0,sIndexOf);
					displayObject = displayObject.hasOwnProperty(name) ? displayObject[name] : DisplayObjectContainer(displayObject).getChildByName(name); // XXX. changed to conform with spark components. Spark components don't allow getChildByName
					
					while (s.indexOf("[") != -1) {
						var sIndexOf1:int = s.indexOf("[");
						var sIndexOf2:int = s.indexOf("]");
						var sPosition:String = s.substring(sIndexOf1 + 1, sIndexOf2);
						if (!sPosition.match(/^\d$/))
							return null;
						var position:int = int(sPosition);
						try {
							displayObject = DisplayObjectContainer(displayObject).getChildAt(position);
						} catch (e:RangeError) {
							return null;
						}
						s = s.substr(0, sIndexOf1) + s.substr(sIndexOf2 + 1);
					}
				} else {
					break;
				}
			}
			
			return displayObject;
			
		}
		
		public static function getPath(displayObject:DisplayObject, root:DisplayObjectContainer = null):String {
		
			if (displayObject == null)
				return null;
					
			var s:String = displayObject.name;
			while ((displayObject.parent != root) && !(displayObject.parent is Stage)) {
				s = displayObject.parent.name + "." + s;
				displayObject = displayObject.parent;
			}
			return s;
			
		}
		
		public static function getTopParent(displayObject:DisplayObject):DisplayObjectContainer {
			
			if (displayObject == null)
				return null;
				
			var topParent:DisplayObjectContainer;
			if (displayObject is DisplayObjectContainer) {
				topParent = DisplayObjectContainer(displayObject);
			} else {
				topParent = displayObject.parent;
			}
			
			while (topParent.parent != null)
				topParent = topParent.parent;
			
			return topParent;
			
		}
		
		
	}
	
}
